<template>
  <div>
    为{{ user.username }}分配角色
    <el-transfer v-model="value" :data="data" :titles="['备选角色', '已有角色']" :props="{key: 'roleId',label: 'roleName'}"></el-transfer>

    <el-button @click="doDistributeRole">分配</el-button>
  </div>
</template>

<script>
import axios from "@/util/request.js";
export default {
  data() {
    return {
      user: {},
      roles: [],
      data: [],
      value: [],
    };
  },
  mounted() {
    this.getUser();
    this.getRoles();
  },
  methods: {
    getUser() {
      // 收集数据
      let userId = this.$route.params.userId;
      // 发送请求
      axios.post("user/findOne", userId, axios.textConfig).then((r) => {
        // 这里的user包含user本身的信息，以及拥有的角色
        this.user = r.data;
        this.value = this.user.roles.map(role => {return role.roleId})
      });
    },
    getRoles() {
      axios.post("role/findAll").then((r) => {
        this.roles = r.data;
        this.data = this.roles;

      });
    },
    doDistributeRole() {
        let userId = +this.$route.params.userId;
        let roleIds = this.value;

        axios.post("user/distributeRoles", {userId, roleIds}).then(r => {
            if(r.code == 200) {
                this.$message.success("分配角色成功")
            } else {
                this.$message.warning("分配角色无效")
            }
        })
        
    }
  },
};
</script>

<style>
</style>